local module = {}
module.name = "TabBinder"
module.Init = function()

	local eventf = CreateFrame("frame")
	eventf:RegisterEvent("ZONE_CHANGED_NEW_AREA")
	eventf:RegisterEvent("PLAYER_REGEN_ENABLED")
	eventf:RegisterEvent("DUEL_REQUESTED")
	eventf:RegisterEvent("DUEL_FINISHED")
	eventf:RegisterEvent("CHAT_MSG_SYSTEM")
	eventf.isFail = false

	eventf:SetScript("OnEvent", function(self, event, ...)
		local arg1, arg2, arg3 = ...

		if event=="CHAT_MSG_SYSTEM" then
			if arg1 == ERR_DUEL_REQUESTED then event = "DUEL_REQUESTED" end
		end
		if event=="ZONE_CHANGED_NEW_AREA" or (event=="PLAYER_REGEN_ENABLED" and self.isFail) or event=="DUEL_REQUESTED" or event=="DUEL_FINISHED" then
			local which, pvpType = GetCurrentBindingSet(), GetZonePVPInfo() or ""
			local _, zoneType = IsInInstance()
			if zoneType==nil then zoneType="" end
			
			tabKey = GetBindingKey("TARGETNEARESTENEMYPLAYER")
			if tabKey == nil then tabKey = GetBindingKey("TARGETNEARESTENEMY") end
			if tabKey == nil then tabKey = "TAB" end
			lastTabKey = GetBindingKey("TARGETPREVIOUSENEMYPLAYER")
			if lastTabKey == nil then lastTabKey = GetBindingKey("TARGETPREVIOUSENEMY") end
			if lastTabKey == nil then lastTabKey = "SHIFT-TAB" end

			local CurrentBind = GetBindingAction(tabKey)

			if (pvpType:find("arena") or pvpType:find("combat")) or zoneType:find("pvp") or event=="DUEL_REQUESTED" then
				if CurrentBind ~= "TARGETNEARESTENEMYPLAYER" then
					local success = SetBinding(tabKey, "TARGETNEARESTENEMYPLAYER")
					SetBinding(lastTabKey, "TARGETPREVIOUSENEMYPLAYER")
					if success == 1 then
						if self.isFail then
							print(""..tabKey.." set to |cff00ccffenemy players only|r.")
						end
						SaveBindings(which)
						self.isFail = false
					else
						print(""..tabKey.." binding |cffff0000failed|r to update.")
						self.isFail = true
					end
				end
			else
				if CurrentBind ~= "TARGETNEARESTENEMY" then
					local success = SetBinding(tabKey, "TARGETNEARESTENEMY")
					SetBinding(lastTabKey, "TARGETPREVIOUSENEMY")
					if success == 1 then
						if self.isFail then
							print(""..tabKey.." set to |cff00ccffall enemies|r.")
						end
						SaveBindings(which)
						self.isFail = false
					else
						print(""..tabKey.." binding |cffff0000failed|r to update.")
						self.isFail = true
					end
				end
			end
		end
	end)

end
tinsert(SuperClassic.modules, module) -- finish him!